<template>
    <div>
        <div>
            <el-card class="box-card" shadow="never" style="width: 99%">
                <div style="max-height: 200px; overflow-y: auto;">
                    <div v-for="item in unassignedCounts" class="session-item">
                        <span style="">{{ `${item.CompeteGroupName} ${item.CompeteEventName} [${item.CompeteCount}]` }}</span>
                        <el-button size="mini" icon="el-icon-plus" circle @click="createSession(item)" style="margin-left: 5px;"></el-button>
                    </div>
                </div>
            </el-card>
        </div>
        <div style="width: 100%; overflow-x: scroll;">
            <div style="display: inline-flex; min-height: 600px;">
                <el-card class="box-card" shadow="hover" style="width: 400px" v-for="date in event_date">
                    <div slot="header" class="clearfix">
                        <span class="bold" style="font-size: 18px;">{{ date.Format('yyyy年MM月dd日') + ' ' + date.getWeekday() }}</span>
                    </div>
                    <el-row>
                        <el-col :span="24">
                            <session-item v-for="sess in sessions[date]" 
                                         :data="sess" 
                                         :juries="juries" 
                                         :rooms="rooms"
                                         @SessionCreated="sessionCreated"></session-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
        </div>
        <el-dialog :title="`新建 ${current.CompeteGroupName} ${current.CompeteEventName} 比赛场次`" 
                   :visible.sync="dialogVisible" width="60%">
            <el-form :model="session" ref="createSessionForm" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="场次名称" prop="SessionName" :rules="[{ required: true, message: '场次名称不能为空'}]">
                            <el-input v-model="session.SessionName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="场次时间" prop="SessionTime" 
                            :rules="[
                                { required: true, message: '场次时间不能为空'},
                                { validator: validateDate, trigger: 'blur' }
                            ]">
                            <el-date-picker v-model="session.SessionTime" type="datetime" style="width: 100%" :clearable="false"
                                            format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" :default-value="event_date[0]"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="场次类型" prop="SessionType">
                            <el-radio-group v-model="session.SessionType">
                                <el-radio-button label="PRELIMINARY">初赛</el-radio-button>
                                <el-radio-button label="REMATCH">复赛</el-radio-button>
                                <el-radio-button label="FINALS">决赛</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="场次时长" prop="SessionDuration">
                            <el-time-select v-model="session.SessionDuration" :picker-options="{ start: '00:00', step: '00:15', end: '10:00' }"> </el-time-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="场次场地">
                            <el-select v-model="session.SessionRoom" filterable placeholder="请选择" style="width: 100%">
                                <el-option v-for="item in rooms" :key="item.RoomId" :label="item.RoomSite" :value="item.RoomSite"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div style="text-align: right; margin-bottom: 10px;">
                <span>总计比赛数量：{{ unassignedCompetes.length }}</span>
                <el-divider direction="vertical"></el-divider>
                <span>本场次比赛数量：{{ selectionCompetes.length }}</span>
                <el-divider direction="vertical"></el-divider>
                <span>按报名优先顺序，选中前</span>
                <el-input-number v-model="rank" controls-position="right" :min="1" :max="100" style="width:100px;"></el-input-number>
                <el-button size="small" type="primary" @click="selectTopCompetes(unassignedCompetes)">选中</el-button>
            </div>
            <el-table v-if="unassignedCompetes!=null" ref="competeTable" :data="unassignedCompetes" stripe border 
               :default-sort="{prop: 'TotalScore', order: 'descending'}" max-height=500 style="width: 100%"
               @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column align="center" prop="CompeteId" label="序号" width="80"></el-table-column>
                <el-table-column align="center" prop="PassportNo" label="通行证" width="130"></el-table-column>
                <el-table-column align="center" label="姓名/团队">
                    <template slot-scope="scope">
                        <span v-if="scope.row.CompeteEvent.indexOf('SOLO')>-1">{{scope.row.Passport.User.Name}}</span>
                        <span v-if="scope.row.CompeteEvent.indexOf('SOLO')==-1">
                            <li class="fa fa-users"></li>
                            {{scope.row.Team.Name}}({{scope.row.Team.Leader.User.Name}})
                        </span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="国家地区" width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.Team!=null">{{scope.row.Team.Leader.User | location}}</span>
                        <span v-if="scope.row.Passport!=null">{{scope.row.Passport.User | location}}</span>                        
                    </template>
                </el-table-column>  
                <el-table-column align="center" prop="MusicName" label="曲目"></el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveSession">确 定</el-button>
            </span>  
        </el-dialog>
    </div>
</template>

<script>
import {DeepClone, LocationStringFormatFromUser}  from 'web/utils';
import SessionItem from './session-item';

export default {
    components: {
        SessionItem
    },
    filters: {
        location: LocationStringFormatFromUser
    },
    data() {
        var validateDate = (rule, value, callback) => {
            let start_date = new Date(this.event_date[0]);
            let end_date = new Date(this.event_date[this.event_date.length-1]);
            let date = new Date(value);
            if (date < start_date || date > end_date) {
                // callback(new Error('场次日期应该在比赛周期内'));
            }
            callback();
        };
        return {
            dialogVisible: false,
            groups: [],
            events: [],
            rooms: [],
            juries: [],
            event_date: [],
            sessions: {},
            session: {},
            rank: 50,
            current: {},
            selectionCompetes: [],
            unassignedCounts:[],
            unassignedCompetes: [],
            validateDate,
        }
    },
    mounted() {

        // 读取项目和组别列表
        Promise.all([
            this.$DataService.GetWordDictByCode('COMPETE_GROUP'),
            this.$DataService.GetWordDictByCode('SOLO_COMPETE_EVENT'),
            this.$DataService.GetWordDictByCode('ENSEMBLE_COMPETE_EVENT')
        ]).then(ret => {
            this.groups = ret[0];
            this.events = Object.assign(ret[1], ret[2]);
        });

        // 读取比赛场地
        this.$DataService.GetRooms().then(ret => this.rooms = ret);

        // 读取评委列表
        this.$DataService.GetJuries().then(ret => this.juries = ret);

        // 读取所有未分配比赛数量
        this.$CompeteService.QueryUnassignedCount().then(ret => this.unassignedCounts = ret);

        // 读取比赛日期
        this.$ConfigService.getConfigsByScope('EVENT_DATE')
            .then(configs => {
                let event_date_start = new Date(configs['EVENT_DATE_START']);
                let event_date_end = new Date(configs['EVENT_DATE_END']);
                while (event_date_start <= event_date_end) {
                    let dt = new Date(event_date_start);
                    this.event_date.push(dt);
                    event_date_start = event_date_start.addDays(1);
                }
                // 加载所有已经创建的场次
                this.loadAllSessions();
            });
    },
    methods: {
        loadAllSessions() {
            this.sessions = {};
            for(let dt of this.event_date) {
                this.sessions[dt] = [];
            }
            this.$SessionService.QuerySessions(null, 1, 999999)
            .then(ret => {
                for(let sess of ret) {
                    this.addSession(sess);
                }
                for (let sessions of Object.values(this.sessions)) {
                    sessions.sort((a, b) => 
                        Math.sign(new Date(a.SessionTime0).getTime() - new Date(b.SessionTime0).getTime()));
                }
                this.$forceUpdate();
            });
        },

        addSession(session) {
            session.SessionTime = new Date(session.SessionTime0).Format('yyyy-MM-dd hh:mm');
            session.CompeteEventName = this.events[session.CompeteEvent];
            session.CompeteGroupName = this.groups[session.CompeteGroup];
            session.SessionDuration = '02:00';
            let dt = new Date(session.SessionTime0).Date();
            if (this.sessions[dt]) {
                this.sessions[dt].push(session);
            }
        },

        createSession(item) {
            this.dialogVisible = true;
            this.current = item;
            this.$CompeteService.QueryUnassignedCompetes(item.CompeteEvent, item.CompeteGroup)
                .then(ret => {
                    this.unassignedCompetes = ret;
                    this.rank = ret.length;
                    if (this.rank > 50) {
                        this.rank = 50;
                    }
                });
            // 默认场次名称
            this.session = {
                SessionName: `${this.current.CompeteGroupName} ${this.current.CompeteEventName} 初赛`,
                SessionType: 'PRELIMINARY',
                SessionTime: '',
                SessionRoom: '',
                SessionDuration: '02:00',
                CompeteEvent: this.current.CompeteEvent,
                CompeteGroup: this.current.CompeteGroup
            };
        },

        selectTopCompetes(rows) {
            this.$refs.competeTable.clearSelection();
            for(let i = 0; i < this.rank; i++) {
                this.$refs.competeTable.toggleRowSelection(rows[i], true);
            }
        },

        handleSelectionChange(val) {
            this.selectionCompetes = val;
        }, 

        sessionCreated(new_session) {
            this.loadAllSessions();
        },

        saveSession() {            
            this.$refs['createSessionForm'].validate((valid) => {
                if (!valid) { return; }
                if (this.selectionCompetes.length == 0) { return; }

                let session = DeepClone(this.session);
                session.SessionCompetes = DeepClone(this.selectionCompetes);
                session.SessionTime0 = session.SessionTime;
                session.SessionTime1 = session.SessionTime;
                session.Recorder = null;
                session.RecordTime = null;
                session.Reviewer = null;
                session.ReviewTime = null;
                session.SessionCompetes.sort((a, b) => {
                    return Math.sign(b.CompeteId - a.CompeteId);
                });
                session.SessionCompetes.forEach((item, index) => {
                    item.SortIndex = index + 1;
                    item.Score0 = null;
                    item.Score1 = null;
                    item.Score2 = null;
                    item.Score3 = null;
                    item.Score4 = null;
                    item.Score5 = null;
                    item.Score6 = null;
                    item.Score7 = null;
                    item.Score8 = null;
                    item.TotalScore = null;
                });
                this.$SessionService.CreateSession(session)
                .then(ret => {
                    if(ret) {
                        this.$notify({
                            title: '创建成功',
                            message: '比赛场次创建成功！',
                            type: 'success'
                        });
                        this.dialogVisible = false;

                        // 将场次添加到对应的日期栏目内
                        this.loadAllSessions();
                    }
                });
            });
        }
    }
}
</script>

<style>
/* .el-card.box-card {
    display: inline-block;
    margin: 5px;
} */

.el-card__body .el-form-item {
    margin-bottom: 5px;
}

.session-item {
    padding: 12px 10px 10px 10px;
    text-align: left; 
    height: 45px;
    display: inline-block;
    border: 1px solid #EBEEF5;
    margin: 5px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    -webkit-box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.bold {
    font-size: 16px; 
    font-weight: 700;
}

.el-drawer__body {
    padding: 20px;
}

.drawer-content {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.drawer-content form{
    flex: 1;
}

.drawer-footer {
    display: flex;
}

.drawer-footer button{
    flex: 1;
}
</style>
